package com.pizidea.imagepicker;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import android.content.Context;
import android.util.Log;
/**
 * @author long
 * copy  modify by meijun
 *
 */
public class Mp3DownloadUtils {

	private static final String TAG = "Mp3DownloadUtils";
	
	private static OkHttpClient mOKHttpClient = new OkHttpClient();
	/**
	 * 
	 * @param urlPath
	 * @param desFilePath
	 */
	public static void downLoadFiles(final Context mContext, String urlPath,
									 final String desFilePath, final DownloadListener downloadListener){
		Log.i(TAG, "---downLoadFiles---");
		Request request = new Request.Builder().url(urlPath).build();

			mOKHttpClient.newCall(request).enqueue(new Callback() {
				@Override
				public void onResponse(Call arg0, Response response) throws IOException {
					if(null != response){
						byteToFile(mContext,response.body().bytes(), desFilePath);
						if (downloadListener != null)
							downloadListener.onSuccess(desFilePath);
					}
				}
				@Override
				public void onFailure(Call arg0, IOException arg1) {
					if (downloadListener != null)
						downloadListener.onFailure();
				}
			});

	}
	/**
	 * byte[]数组转为file文件
	 * @param datas
	 * @param desFilePath 目标文件存储路径
	 */
	private static void byteToFile(Context mContext,byte[] datas,String desFilePath){
		File file = new File(desFilePath);
		InputStream is = new ByteArrayInputStream(datas);
		byte[] buf = new byte[2048];
		int len = 0;
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file);
			long sum = 0;
	        while ((len = is.read(buf)) != -1) {
	            fos.write(buf, 0, len);
	            sum += len;
	        }
	        fos.flush();
	        Log.d(TAG, "文件生成成功");

		} catch (Exception e) {
			e.printStackTrace();
			Log.d(TAG, "文件生成失败");
		}finally{
			 try {
                 if (is != null)
                     is.close();
             } catch (IOException e) {
             }
             try {
                 if (fos != null)
                     fos.close();
             } catch (IOException e) {
             }
		}
		
	}
	


	public interface DownloadListener{

		 void onSuccess(String path);
		 void onFailure();

	}

}
